package library.and.xps.com.step.view.activity;

import android.content.Intent;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jude.utils.JUtils;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.ListHolder;
import com.orhanobut.dialogplus.OnItemClickListener;
import com.orhanobut.dialogplus.ViewHolder;
import com.squareup.okhttp.Request;

import java.util.List;

import library.and.xps.com.step.R;
import library.and.xps.com.step.URLConstants;
import library.and.xps.com.step.adapter.DepartmentsAdapterInTeamManagerDailog;
import library.and.xps.com.step.adapter.MemberListAdapterInDepartDetailAdapter;
import library.and.xps.com.step.m.model.MemberInDepartment;
import library.and.xps.com.step.m.model.MoveMember;
import library.and.xps.com.step.m.model.TeamManager;
import library.and.xps.com.step.m.netapi.OkHttpClientUtils;
import library.and.xps.com.step.net.ResponceWrapper;
import library.and.xps.com.step.util.HttpResponsHelper;
import library.and.xps.com.step.util.RequestCallback;
import library.and.xps.com.step.view.base.BaseActivity;

public class DepartmentDetailActivity extends BaseActivity {
    TextView tv_title, tv_actionbarRight, tv_dep_name;
    TeamManager.ListBean thisDepartment;
    ListView lv_member;
    MemberListAdapterInDepartDetailAdapter memberListAdapterInDepartDetailAdapter;
    List<TeamManager.ListBean> allDepartments;
    private final String REQUEST_DEPARTMENTS = "REQUEST_DEPARTMENTS";
    private final String REQUEST_MOVEMEMBER = "REQUEST_MOVEMEMBER";

    MemberInDepartment.ListBean selectedMember;

    @Override
    protected int getLayout() {
        return R.layout.activity_department_detail;
    }

    @Override
    protected void setData() {
        Intent i = getIntent();
        thisDepartment = (TeamManager.ListBean) i.getSerializableExtra("department_click");
        if (thisDepartment == null) return;
        tv_title.setText(thisDepartment.getDname());
        tv_dep_name.setText(thisDepartment.getDname());

        memberListAdapterInDepartDetailAdapter = new MemberListAdapterInDepartDetailAdapter(this);
        lv_member.setAdapter(memberListAdapterInDepartDetailAdapter);
        lv_member.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                List<MemberInDepartment.ListBean> data = ((MemberListAdapterInDepartDetailAdapter) parent.getAdapter()).getData();
                selectedMember = data.get(position);
                showdialog("将成员移动到:");
            }
        });

        getUsersInTeam(thisDepartment.getDepartmentid() + "");
        getDepartments();

    }

    void getUsersInTeam(String departmentId) {
        if (getUser() == null) return;
        String data = URLConstants.TEAM.ManageDepartmentUsers + "?userid=" + getUser().getUserid() + "&departmentid=" + departmentId;
        OkHttpClientUtils.getDataAsync(this, data, new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                dissmisDialog();
                e.printStackTrace();
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                dissmisDialog();
                MemberInDepartment memberInDepartment = new Gson().fromJson(response.getBody(), MemberInDepartment.class);
                if (HttpResponsHelper.SuccessResponce(memberInDepartment)) {
                    memberListAdapterInDepartDetailAdapter.setData(memberInDepartment.getList());

                    int memberCount = memberInDepartment.getList().size();
                    tv_actionbarRight.setText("共" + memberCount + "人");
                }
            }

            @Override
            public void onStart() {
                showDialogNoCancel();
            }
        }, REQUEST_DEPARTMENTS);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpClientUtils.cancelCall(REQUEST_DEPARTMENTS);
        OkHttpClientUtils.cancelCall(REQUEST_MOVEMEMBER);
    }

    @Override
    protected void init() {
        r2v(R.id.actionbar_iv_back).setOnClickListener(this);
        tv_title = r2v(R.id.actionbar_tv_title);
        lv_member = r2v(R.id.lv_member);
        tv_dep_name = r2v(R.id.tv_dep_name);
        tv_actionbarRight = r2v(R.id.actionbar_tv_right);
        tv_actionbarRight.setVisibility(View.VISIBLE);
        tv_actionbarRight.setText("共10人");
        tv_actionbarRight.setTextColor(R.color.colorPrimary);

    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.actionbar_iv_back:
                finish();
                break;
        }
    }

    void showdialog(String hintText) {
        ViewHolder headerViewHolder = new ViewHolder(getLayoutInflater().inflate(R.layout.header, null));
        View headerView = headerViewHolder.getInflatedView();

        ((TextView) headerView.findViewById(R.id.tv_hint)).setText(hintText);
        DialogPlus dialog = DialogPlus.newDialog(this)
                .setContentHolder(new ListHolder())
                .setGravity(Gravity.CENTER)
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(DialogPlus dialog, Object item, View view, int position) {

                        TeamManager.ListBean department = (TeamManager.ListBean) item;
                        moveMember(selectedMember.getUserid() + "",
                                department.getDepartmentid() + "",
                                thisDepartment.getDepartmentid() + "");

                        dialog.dismiss();
                    }
                })
                .setInAnimation(R.anim.dialog_in_anim)
                .setOutAnimation(R.anim.dialog_out_anim)
                .setAdapter(new DepartmentsAdapterInTeamManagerDailog(this, allDepartments))
                .setExpanded(true, 700)
                .setHeader(headerView)
                .create();
        dialog.show();

    }

    /**
     * 移动成员
     *
     * @param userId      被移动人员ID
     * @param oldDepartId 用户当前所在的部门ID
     * @param newDepartId 移动到的部门ID
     */
    void moveMember(String userId, String newDepartId, String oldDepartId) {
        String data = URLConstants.TEAM.MoveMember + "?userid=" + userId + "&olddeptid=" + oldDepartId + "&newdeptid=" + newDepartId;

        OkHttpClientUtils.getDataAsync(this, data, new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                dissmisDialog();
                e.printStackTrace();
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                dissmisDialog();
                MoveMember moveMember = new Gson().fromJson(response.getBody(), MoveMember.class);
                if (HttpResponsHelper.SuccessResponce(moveMember)) {
                    getUsersInTeam(thisDepartment.getDepartmentid() + "");
                    getDepartments();
                } else {
                    JUtils.Toast("移动成员失败");
                }
            }

            @Override
            public void onStart() {
                showDialogNoCancel();
            }
        }, REQUEST_MOVEMEMBER);
    }

    //获取所有部门
    void getDepartments() {
        if (getUser() == null) return;
        String data = URLConstants.TEAM.ManageDepartment + "?userid=" + getUser().getUserid() + "&teamid=" + getUser().getTeams().get(0).getTId();
        OkHttpClientUtils.getDataAsync(this, data, new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                dissmisDialog();
                e.printStackTrace();
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                dissmisDialog();
                TeamManager teamManager = new Gson().fromJson(response.getBody(), TeamManager.class);
                if (HttpResponsHelper.SuccessResponce(teamManager)) {
                    allDepartments = teamManager.getList();
                }
            }

            @Override
            public void onStart() {
                showDialogNoCancel();
            }
        }, "");
    }

}
